#!/usr/bin/env python

#import sqlite argparser
import sqlite3, argparse

#This script can be used to retrieve undeleted call history from the iPhone

from time import strftime, localtime, gmtime
callTypeFlag= {
	4 : 'Incoming', 
	65540 : 'Incoming', 
	5 : 'Outgoing', 
	65541 : 'Outgoing', 
	8 : 'Cancelled'
}


def run(s):
	#check if the file call_history.db is there
	try:
		print('Found "{}"'.format(s))
		#connect to the db

		conn = sqlite3.connect(s)
		c = conn.cursor()
		#print the column headers
		print()
		#get the table to print
		for ROWID, address, date, duration, flags, id, name, country_code in c.execute('select  ROWID, address, date, duration, flags, id, name, country_code from call'):
			#convert the time to the usual format
			time = strftime('%Y-%m-%d %H:%M:%S (%Z)', localtime(date))
		
			row = str(ROWID)
			
			#duration = str(duration)
			formattedFlags = callTypeFlag.get(flags)

			#prints the values
			print('{0:10}{1:15}{2:30}{3:20}{4:20}{5:10} {6:10} {7:10}'.format(row, address, time, duration, formattedFlags.rjust(20), id, name, country_code))

		#endofloop
			
	except sqlite3.Error:
		print('The call_history.db is not placed in the current working directory')    

	

def main():
	#execute the operation on the call_history.db file
	
	databaseName = 'call_history.db'
	run(databaseName)

#exec main
if __name__ == '__main__':
	main()